//
//  WelcomeView.swift
//  WeiBo2017
//
//  Created by 王璐 on 2017/4/27.
//  Copyright © 2017年 wl. All rights reserved.
//

import UIKit
import SDWebImage

/// 欢迎视图
class WelcomeView: UIView {

    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        print("\(classForCoder)\(#function)")
    }
    
    /// 添加到父视图
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        print("\(#function)")

    }
    
    /// 添加到窗口 - 已经显示
    override func didMoveToWindow() {
        super.didMoveToWindow()
        print("\(#function)")

        avatarView.snp.updateConstraints { (make) in
            make.centerY.equalTo(self).offset(-100)
        }
        
        //damp:弹力 越小越弹 0~1
        //Velocity,速度为10,符合重力规则
        UIView.animate(
            withDuration: 2.5,
            delay: 0.0,
            usingSpringWithDamping: 0.9,
            initialSpringVelocity: 10,
            options: [],
            animations: { 
                self.layoutIfNeeded()
        }) { (true) in
            
            self.removeFromSuperview()
        }
    }
    
    /// 布局子视图 - 自动布局设置完成后调用
    //有可能调用非常频繁,一定不要太耗时的操作
    override func layoutSubviews() {
        super.layoutSubviews()
        print("\(#function)")
    }
    
    // MARK: - 私有控件
    /// 欢迎视图
    fileprivate lazy var avatarView = UIImageView(wl_imageName: "avatar_default_big")
    /// 欢迎标签
    fileprivate lazy var welcomeLabel :UILabel = UILabel(wl_text: "欢迎回来", fontSize: 18)

}

// MARK: - 设置界面
extension WelcomeView {
    
    fileprivate func setupUI(){
        
        //1.设置背景
        backgroundColor = UIColor(patternImage: UIImage(named: "ad_background")!)
        //2.添加控件
        addSubview(avatarView)
        addSubview(welcomeLabel)
        
        //图像变成圆形
        let icon_WH :CGFloat = 46
        avatarView.layer.cornerRadius = icon_WH
        avatarView.layer.masksToBounds = true
        
        //3.自动布局
        avatarView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self).offset(80)
            make.size.equalTo(CGSize(width: icon_WH*2, height: icon_WH*2))
        }
        welcomeLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(avatarView)
            make.centerY.equalTo(avatarView.snp.bottom).offset(20)
        }
        
        //4.强行更新约束
        layoutIfNeeded()
        
        //5.设置图像
        avatarView.wl_setImageWithURL(urlString: UserCount.sharedUserCount.avatar_large, placeholderName: "avatar_default_big")
        
    }
}
